/**
 * Created by shenc on 2016/3/30.
 * 后台-添加产品页
 */

//生成产品table
function Products(options) {
    var config = {
        type: 'add',
        url: '/admin/product'
    };
    var This = this;
    var chkForm = $('.J-chkForm');            //表单
    var submitBtn = chkForm.find(':submit');
    var productBox = $('#productBox');      //table 盒子
    var proType = $('#J-proType');          //产品分类 select
    var checkWrap = $('.J-checks');         //checkbox 盒子
    var groupTpl = $('#groupTpl').html();   //checkbox分组 tpl
    var checkTpl = $('#checkTpl').html();   //checkbox tpl
    var table = $($('.J-tableTpl').html()).clone(); //table tpl
    var alertModal = $('#alertModal');      //提示框
    var selParams = [];
    var selParamsVal = [];
    var attributeObj = {};
    var storageData = {};

    $.extend(config, options || {});

    //根据类型生成checkbox
    proType.on('change', function () {
        var id = proType.val();

        //ajax获取属性数据
        $.ajax({
            url: '/admin/category_attribute/get_attribute',
            data: {cat_id: id},
            dataType: 'json',
            type: 'get',
            success: function (res) {
                tools.log('res', res);
                if (res.length) {
                    This.initICheck(res);
                } else {
                    checkWrap.empty();
                    This.clear();
                }

            }
        });

    });

    //提交表单
    chkForm.on('submit', function (e) {
        e.preventDefault();

        //todo 1表单验证
        //1表单验证
        var error = chkForm.find('.has-error');
        if (error.length) {
            error.eq(0).find('input').focus();
            submitBtn.prop('disabled', true);
            alertModal.find('.modal-body').text('绑定商品ID不存在');
            alertModal.modal();
            return false;
        }


        //2数据格式化
        var data = [];
        var inputs = productBox.find('.J-opts input').filter(function () {
            return $(this).val() !== '';
        });

        for (var i = 0; i < inputs.length; i++) {
            var curInput = inputs.eq(i);
            data.push({
                goods_id: curInput.val(),
                attribute_value: (curInput.closest('tr').data('ids') + '').split(',')
            });
        }

        var formData = {
            product_name: $('#J-nameInput').val(),
            cat_id: proType.val(),
            attribute_value_arr: attributeObj,
            goods_value_arr: data
        };


        //3提交
        var url='',type='';
        if (config.type == 'edit') {
            url=config.url+'/'+$('#productId').val();
            type='put';
        }else{
            url=config.url;
            type='post';
        }

        $.ajax({
            url: url,
            data: formData,
            dataType: 'json',
            type: type,
            success: function (res) {
                if (res.status) {
                    window.location.href = '/admin/product';
                } else {
                    alertModal.find('.modal-body').text(res.message);
                    alertModal.modal();
                }
            }
        });
    });

    //icheck 插件
    this.initICheck = function (curData) {
        var groupArr = [], checks;

        if (typeof curData === 'undefined' || curData.length == 0) return false;

        for (var i = 0; i < curData.length; i++) {
            var curType = curData[i], checkHtml = [];
            for (var j = 0; j < curType.attribute_value.length; j++) {
                checkHtml.push(tools.htmlTemplate(checkTpl, curType.attribute_value[j]));
            }
            groupArr.push(tools.htmlTemplate(groupTpl, $.extend(true, {}, curType, {checkHtml: checkHtml.join('')})));

        }

        checkWrap.html(groupArr.join(''));

        checks = $('input[type="checkbox"].minimal, input[type="radio"].minimal', checkWrap);
        checks.iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass: 'iradio_minimal-blue'
        });

        checks.on('ifChanged', function () {
            This.makeTable();
        });
        This.makeTable();
    };

    //清除历史数据
    this.clear = function () {
        selParams = [];
        selParamsVal = [];
        attributeObj = {};
        productBox.html('<div class="form-control-static">无</div>');
        submitBtn.prop('disabled', true);
    };

    //绑定table中的事件
    this.bind = function () {
        //激活提交按钮
        submitBtn.prop('disabled', false);

        //远程验证绑定商品的id是否存在
        productBox.off('input').on('input', '.J-opts input', function () {
            var jqInput = $(this),
                wrap = jqInput.closest('.has-feedback'),
                trId = jqInput.closest('tr').attr('id'),
                id = jqInput.val(),
                timer = jqInput.data('timer') || 0;

            submitBtn.prop('disabled', true);

            if (id == '') {
                clearTimeout(timer);
                wrap.removeClass('has-success has-error');
                wrap.find('.glyphicon').addClass('sr-only');
                submitBtn.prop('disabled', false);
                return false;
            }

            //缓存数据
            This.setInfo(trId, id);

            clearTimeout(timer);
            //异步验证商品id
            timer = setTimeout(function () {
                $.ajax({
                    url: '/admin/goods/is_has_goods/' + id,
                    dataType: 'html',
                    type: 'get',
                    success: function (res) {
                        tools.log(res);
                        wrap.toggleClass('has-success', res == 'true');
                        wrap.toggleClass('has-error', res != 'true');
                        wrap.find('.glyphicon-ok').toggleClass('sr-only', res != 'true');
                        wrap.find('.glyphicon-remove').toggleClass('sr-only', res == 'true');

                        submitBtn.prop('disabled', res != 'true');
                    }
                });
            }, 500);

            jqInput.data('timer', timer);

        });
    };

    //获取选中数据
    this.makeData = function () {
        var params = $('.J-params');//属性组
        This.clear();
        params.has(':checked').each(function () {
            var that = $(this),
                pId = that.data('id'),
                pName = that.data('name'),
                checkedItems = that.find(':checked'),
                cArr = [],
                idArr = [];


            for (var i = 0; i < checkedItems.length; i++) {
                var curItem = checkedItems.eq(i),
                    cId = curItem.data('id');
                cArr.push({id: cId, name: curItem.closest('label').text()});
                idArr.push(cId);
            }

            selParams.push({id: pId, name: pName});
            selParamsVal.push(cArr);
            attributeObj[pId] = idArr;
        });
    };

    //渲染table
    this.makeTable = function () {
        This.makeData();//获取数据

        var th = [], thead, tbody, rowNum = 1;
        var optsHtml = '<td class="J-opts">'
            + '<div class="has-feedback">'
            + '<input type="text" class="form-control input-sm" value="${goods_id}">'
            + '<span class="glyphicon glyphicon-ok form-control-feedback sr-only"></span>'
            + '<span class="glyphicon glyphicon-remove form-control-feedback sr-only"></span>'
            + '</div>'
            + '</td>';

        if (selParams.length == 0) return false;

        //表头
        for (var i = 0; i < selParams.length; i++) {
            th.push('<th data-id="' + selParams[i].id + '">' + selParams[i].name + '</th>');//生成表头
            rowNum *= selParamsVal[i].length;//总排列组合数
        }
        thead = '<tr>' + th.join('') + '<th>绑定商品ID</th></tr>';
        table.find('thead').html(thead);

        tools.log('总行数：', rowNum);

        //生成列表中的行
        //首先将每个行对应td定义成一个空数组，后面要用
        var trs = [], trsId = [], singleRowNum = 1, oldRow = 1;
        for (var j = 0; j < rowNum; j++) {
            trs[j] = [];
            trsId[j] = [];
        }

        //
        // 循环生产td标签（不限制属性个数，不限制属性值个数，但是不要太多，最终生成的table行数会成数量级增加，对此我表示很无奈）
        // 这块有点绕
        // 1层循环属性类型；
        // 2层循环历史循环（本次循环的前一次）对应属性类型所占据的行数（此循环生成oldSide的值，在第三层循环中用来确定特定属性值循环显示的起始位置）；
        // 3层循环特定属性对应的值数组的长度 以此来确定该属性值显示的起始行数（1列对应1个特定属性，该属性的所有值在此列显示，一行代表一个SKU）
        // 4层按照3层确定的起始行生产td标签
        //
        for (var k = 0; k < selParams.length; k++) {
            var cur = selParamsVal[k];

            singleRowNum = singleRowNum * cur.length;//当前单个属性重复行数
            for (var b = 0; b < oldRow; b++) {
                var oldSide = b * rowNum / oldRow;

                for (var a = 0; a < cur.length; a++) {
                    var startNum = oldSide + a * rowNum / singleRowNum;
                    var endNum = startNum + rowNum / singleRowNum;
                    var item = cur[a];

                    for (var c = startNum; c < endNum; c++) {
                        if (rowNum / singleRowNum > 1 && c == startNum) {
                            trs[c].push('<td rowspan="' + rowNum / singleRowNum + '" data-id="' + item.id + '">' + item.name + '</td>');
                        } else if (rowNum / singleRowNum == 1) {
                            trs[c].push('<td data-id="' + item.id + '">' + item.name + '</td>');
                        }
                        trsId[c].push(item.id);
                    }

                }
            }

            oldRow = singleRowNum;
        }

        //生成tr结构
        for (var d = 0; d < rowNum; d++) {
            //todo 获取历史输入值
            var curParamsId = 'params_' + trsId[d].join('_');
            var curGoodsId = This.getInfo(curParamsId);
            var curOptsHtml = tools.htmlTemplate(optsHtml, {goods_id: curGoodsId});

            trs[d].unshift('<tr id="params_' + trsId[d].join('_') + '" data-ids="' + trsId[d].join() + '">');
            trs[d].push(curOptsHtml);
            trs[d].push('</tr>');
            trs[d].join('');
        }
        table.find('tbody').html(trs.join(''));
        productBox.empty().append(table);

        //绑定列表事件
        This.bind();

    };


    //初始化
    this.init = function (info) {
        info = JSON.parse(info);
        tools.log('After JSON:', info);

        //todo 非空判断
        //初始化icheck插件
        This.initICheck(info.category_attribute_value);

        //选中历史数据
        $.each(info.attribue_value_arr, function () {
            var curAttr = $(this);
            for (var i = 0; i < curAttr.length; i++) {
                $('#checkBox_' + curAttr[i]).iCheck('check');
            }
        });


        //填写tabel中绑定的商品id
        for (var j = 0; j < info.goods_value_arr.length; j++) {
            var id = 'params_' + info.goods_value_arr[j].attribute_value.join('_');
            var curTr = $('#' + id);

            if (curTr.length) {
                curTr.find('input').val(info.goods_value_arr[j].goods_id);
            }

            //存储历史数据
            This.setInfo(id, info.goods_value_arr[j].goods_id);

        }

    };

    //设置缓存
    this.setInfo = function (id, value) {
        storageData[id] = value;
    };

    //读取缓存
    this.getInfo = function (id) {
        var result = '';

        if (typeof storageData[id] != 'undefined') {
            result = storageData[id];
        }

        return result;
    };
}